
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**厦门航空
 * @author 0707
 * @date 2011-3-12
 * @description TODO
 */
public class GetFlightListMF {


	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "et.xiamenair.cn");
		    header.put("Referer", "http://www.xiamenair.com.cn/");
 
			//使用Get请求，赋值url的参数
			 StringBuffer urlBuffer = new StringBuffer();
			
			 urlBuffer.append("http://et.xiamenair.cn/xiamenair/SearchFlights.do?");
			 urlBuffer.append("adultsCount=1&childrenCount=0&isIntlLine=true&isintlflight=domestic&queryType=limit&tripType=ONEWAY");
			 urlBuffer.append("&orgCity=").append(queryInfo.getOrgCity());
			 urlBuffer.append("&dstCity=").append(queryInfo.getDesCity());
			 urlBuffer.append("&takeoffDate=").append(queryInfo.getDateString());
 
	        try {
	        	//返回的HTML
				responseText = proxy.doRequest(
				urlBuffer.toString(), null, header,"GBK");
				resultInfo = (ResultInfo)analyzeResopnseText(responseText);
	 
			}catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
	        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
	
	          	return resultInfo;
			 
		}
		
		
		/**
		 * 根据山东航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象

		      if (source==null||source.trim().length()==0) {
				return null;
			}
		      
		    //因为厦门航空返回的HTML包含了‘明折明扣’，‘网上专享’，‘双程优惠’等不同活动的价格，此处只取网上专享的价格
		      String firstRegex = "<tr id=\"tr02\" style=\"display:.*?\">(.*?)<tr id=\"tr05\" style=\"display:.*?\">";
              Pattern firstPattern = Pattern.compile(firstRegex);
              Matcher firstMatcher = firstPattern.matcher(source);
		      if (firstMatcher.find()) {
		    	  source = firstMatcher.group(1);
			}
		      //匹配‘网上专享’内容end
 
	 		  String[] parts = source.split("<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\">"); //将每一个航班区分开来
		 		  if (parts.length==0) {     //没有航班信息
				System.out.println("厦门航空没有相应航班信息------------------------------");
				return null;
			}
 
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			     regexSB.append("<td\\s*height=\"50\"\\s*width\\s*=\\s*\"70\"\\s*align=\"center\"\\s*valign=\"middle\"\\s*bgcolor=\"#B8E6FE\">(.*?)</td>\\s*");   //航班号
			      regexSB.append(".*?<td\\s*align=\"center\"\\s*valign=\"middle\"\\s*bgcolor=\"#B8E6FE\">(.*?)<br>(.*?)</td>\\s*");  //起飞时间；到达时间
			      regexSB.append("<td\\s*align=\"center\"\\s*valign=\"middle\"\\s*bgcolor=\"#B8E6FE\"\\s*width=\"80px\">(.*?)<br\\s*/>(.*?)</td>");  //是否经停
			      regexSB.append(".*?<td\\s*align=\"center\"\\s*valign=\"middle\"\\s*bgcolor=\"#FFCC33\">剩余座位<br\\s*/>\\s*<label>\\s*<input\\s*type=\"radio\"\\s*name=\"selectradio0\"\\s*value=(.*?)\\s*/>\\s*</label>.*?</td>");
 
			     //航班号  ，航班号+代码共享 ，出发时间，降落时间。
			     String regex =regexSB.toString();
			     
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
 

			     FlightInfo tempInfo = null;
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
			     //依次取出每个航班的信息,因为parts[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
			     Matcher matcher = p.matcher(parts[j]);
			     if(matcher.find())   //匹配航班信息
			     {	    	 

			    	 String flightNo = matcher.group(1).trim();
			    	 //String flightNoAndShareCode = matcher.group(2).trim();
			    	 tempInfo.setFlightNo(flightNo);  //航班号

			    	 tempInfo.setTakeOffTime(matcher.group(2).trim());
			    	 tempInfo.setArriveTime(matcher.group(3).trim());
			    	 tempInfo.setPlaneType(matcher.group(4).trim());
			    	 //判断是否经停
			    	  String stopOverSource = matcher.group(5).trim();
			    	   if (stopOverSource!=null&&stopOverSource.length()>0) {
			    		   if (!stopOverSource.equals("无经停")) {
			    			   tempInfo.setStopOver(true);
						}
						
					}
			    	   //匹配是否有座位
			    	   String haveSeat1 = matcher.group(6).trim();
			    	   //String haveSeat2 = matcher.group(7).trim();
			    	   if (haveSeat1.equals("\"-\"  disabled")) {  //米有座位了
						tempInfo.setHaveSeat(false);  
					}
			     }
			     
			      //舱位&remind
			     String  cabinRegexBefore = "<td\\s*width=\"90\"\\s*align=\"center\"\\s*bgcolor=\"#D6DFE8\"\\s*class=\"text12b_656565\">舱(&nbsp;)*位</td>(.*?)</tr>";
			     Pattern cabinPatternBefore = Pattern.compile(cabinRegexBefore);
			     Matcher cabinMatcherBefore = cabinPatternBefore.matcher(parts[j]);
			     String  cabinSource  = "";
			     if (cabinMatcherBefore.find()) {
			    	 cabinSource = cabinMatcherBefore.group(2);
			    	// System.out.println(cabinSource);
				}
			     
			     String cabinRegex = "<td\\s*align=\"center\"\\s*bgcolor=\"#EDF6FF\">(?!<)(.*?)</td>";
			     Pattern cabinPattern = Pattern.compile(cabinRegex);
			     Matcher cabinMatcher = cabinPattern.matcher(cabinSource);
 
			     String cabin = "";
			     while (cabinMatcher.find()) { 
			    	 priceInfo = new PriceInfo();
			    	 cabin = cabinMatcher.group(1).trim();
			    
                       if (cabin==null||cabin.length()!=1) {
     			    	  //@TODO  记得要抛出异常 
   						System.out.println("厦门航空匹配价格错误");
   						resultInfo.setStatus(-100);
					}
			    	 StringBuffer remind = new StringBuffer();
			    	 priceInfo.setSpace(cabin);
			    	 
			    	 if (cabin.equals("P")||cabin.equals("F")||cabin.equals("J")||cabin.equals("Y")||cabin.equals("B")||cabin.equals("H")||cabin.equals("K")||cabin.equals("L")||cabin.equals("M")||cabin.equals("N")||cabin.equals("Q")||cabin.equals("T")) {
			    		 remind.append("同等舱免费变更航班/日期 ；");
			    		 if (cabin.equals("P")||cabin.equals("F")||cabin.equals("J")||cabin.equals("Y")) {
			    			 remind.append("退票收取票面价5%的退票费；允许签转");
						}
			    		 if (cabin.equals("B")||cabin.equals("H")||cabin.equals("K")) {
			    			 remind.append("退票收取票面价10%的退票费；不得签转");
						}
			    		 if (cabin.equals("L")||cabin.equals("M")||cabin.equals("N")||cabin.equals("Q")||cabin.equals("T")) {
			    			 remind.append("退票收取票面价20%的退票费；不得签转");
						} 
					}else if (cabin.equals("V")||cabin.equals("X")||cabin.equals("R")) {
						 remind.append("每次变更航班/日期收取票面价20%的变更费 ；退票收取票面价30%的退票费；不得签转");
					} 
			    	 priceInfo.setRemind(remind.toString().trim());
			    	 priceList.add(priceInfo);
				}
			     
			     //价格
                 String  priceRegex = "<td align=\"center\" bgcolor=\"#EDF6FF\" class=\"text14b_FF6633\">(.*?)</td>";
			     Pattern pricePattern = Pattern.compile(priceRegex);
			     Matcher priceMacMatcher = pricePattern.matcher(parts[j]); 
			     
		    	 double tempMinPrice = 0.0;
		    	 double tempMaxPrice = 0.0;
		    	 boolean isFirst = true;
			     for (int i = 0; i < priceList.size(); i++) {
			    	 priceInfo = (PriceInfo)priceList.get(i);
			    	 String priceString = "";
			    	 if (priceMacMatcher.find()) {
			    		 priceString =  priceMacMatcher.group(1);
			    		 priceString =  priceString.replace(",",""); //将逗号去掉
			    		 ((PriceInfo)priceList.get(i)).setPrice(Double.parseDouble(priceString));
			    		 }
			    	 else {
			    	  //@TODO  记得要抛出异常 
						System.out.println("厦门航空匹配价格错误");
						resultInfo.setStatus(-100);
					}
			    	  //一个航班不同cabin的最低和最高价格获取
			    	  if (isFirst) {
			    		  tempMinPrice = priceInfo.getPrice();
			    		  tempMaxPrice = priceInfo.getPrice();
			    		  tempInfo.setMinprice(tempMinPrice);
			    		  tempInfo.setMaxprice(tempMaxPrice);
			    		  isFirst = false;
					}
			    	 
					     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = priceInfo.getPrice();
							}
					     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = priceInfo.getPrice(); 
						}
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
				}
			     tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll); 
 		     	 }
 		     	 
 		    resultInfo.setResultList(flightInfos);	  
 		 	 
			return resultInfo;
		}



}
